class User < ActiveRecord::Base
  has_one :college
  
  #unencrypted password
  attr_accessor :password

  
  #validation
  validates_length_of :email, :within => 3..100
  validates_uniqueness_of  :user_name, :case_sensitive => false

  validates_presence_of :name
  validates_presence_of :email
  validates_presence_of :user_name
  validates_length_of  :password, :within => 4..20, 
    :if =>  :password_required?
  validates_confirmation_of :password, :if => :password_required?
  validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :on => :create, :message => "Please format your email address"
  #actually encrypt the password
  before_save :encrypt_password
  
  #encrypts with a given salt
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end
  
  def self.authenticate(user_name, password)
    user = find_by_user_name(user_name)
    user && user.authenticated?(password) ? user : nil
  end
  
  def authenticated?(password)
    encrypted_password == password #User.encrypt(password, salt)
  end
  
  
  protected
  
  #before you save, create salt, encrypt pass
  def encrypt_password
    return if password.blank?
#    if new_record?
#      self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{user_name}--")
#    end
    self.encrypted_password = password # User.encrypt(password, salt)
  end

  def password_required?
    encrypted_password.blank? || !password.blank?
  end
end
